package sskj.regulatory.presentation.decorator

import android.content.Context
import android.content.res.TypedArray
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.support.v4.view.ViewCompat
import android.support.v7.widget.RecyclerView
import android.view.View


class GridDividerItemDecoration(context: Context?, private val mSpanCount: Int) : RecyclerView.ItemDecoration() {
    private val mDivider: Drawable?

    init {
        val a = context?.obtainStyledAttributes(ATTRS)
        mDivider = a?.getDrawable(0)
        a?.recycle()
    }

    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State?) {
        super.onDraw(c, parent, state)
        val childCount = parent.childCount
        for (i in 0 until childCount) {
            val child = parent.getChildAt(i)
            val position = parent.getChildLayoutPosition(child)
            var column = (position + 1) % mSpanCount
            column = if (column == 0) mSpanCount else column

            val params = child
                    .layoutParams as RecyclerView.LayoutParams
            val top = child.bottom + params.bottomMargin +
                    Math.round(child.top.toDouble())
            val bottom = top + mDivider!!.intrinsicHeight
            val left = child.right + params.rightMargin +
                    Math.round(child.left.toDouble())
            val right = left + mDivider.intrinsicHeight

            mDivider.setBounds(child.left, top.toInt(), right.toInt(), bottom.toInt())
            mDivider.draw(c)

            if (column < mSpanCount) {
                mDivider.setBounds(left.toInt(), child.top, right.toInt(), bottom.toInt())
                mDivider.draw(c)
            }

        }
    }


    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State?) {
        val position = parent.getChildLayoutPosition(view)
        if ((position + 1) % mSpanCount > 0) {
            outRect.set(0, 0, mDivider!!.intrinsicWidth, mDivider.intrinsicHeight)
        } else {
            outRect.set(0, 0, 0, mDivider!!.intrinsicHeight)
        }
    }

    companion object {
        private val ATTRS = intArrayOf(android.R.attr.listDivider)
    }
}
